﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.NetworkAnalyst;
using ESRI.ArcGIS.CatalogUI;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;

namespace ISchool
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        #region 系统预设
        //预置地址GDB
        private string IGdbPath = "";
        private string ITiffPath = "";

        //鹰眼功能是否打开
        bool isEagleEye = false;

        #endregion

        #region 活动变量
        //判断窗体是否可以开始移动
        private bool mMouseMove = false;
        //活动变量，获取鼠标即时位置，用于窗体移动
        private int _x = 0;
        private int _y = 0;


        //判断是否工具可以开始移动
        private bool PanelToolDown = false;
        //活动变量，获取鼠标即时位置，用于菜单条移动
        private int pX_menu = 0;
        private int pY_menu = 0;
        //同上，针对工具条移动
        private int pX_tools = 0;
        private int pY_tools = 0;
        //拖动许可
        private bool _IsDrag = false;

        //地图文档方法
        //MapDocumentClass m_MapDocument = new MapDocumentClass();

        //加载地图地址
        private string m_mapDocumentName = string.Empty;

        //定义公用对象
        //private ITOCControl2 m_tocControl;
        //private AxMapControl m_mapControl;
        //private IToolbarMenu m_menuLayer;

        //下拉菜单的整体化
        private PanelList tPanel;
        //下拉菜单是否已出现（未出现为False）
        private bool PanelIsOut = false;


        IPoint pPointStd;
        List<double> st = new List<double>(100);
        public IPointCollection pc;
        public IPolyline pl = new PolylineClass();
        IPointCollection pPs = new PolygonClass();
        #endregion



        #region 无边框窗体移动
        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mMouseMove = true;
                _x = MousePosition.X;
                _y = MousePosition.Y;
            }
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (mMouseMove == true)
            {
                _x = MousePosition.X - _x;
                _y = MousePosition.Y - _y;
                //.Location = new Point(this.Location.X+_x, this.Location.Y+_y);
                this.Location = new System.Drawing.Point(this.Location.X + _x, this.Location.Y + _y);
                _x = MousePosition.X;
                _y = MousePosition.Y;
            }
        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            mMouseMove = false;
        }
        #endregion
        #region 鹰眼功能的开启关闭
        //作者：郭菲
        //描述：鹰眼的开关
        private void label4_Click(object sender, EventArgs e)
        {
            if (isEagleEye == false)
            {
                axMapControl2.Visible = true;
                this.panel11.BorderStyle = BorderStyle.Fixed3D;
                isEagleEye = true;
            }
            else
            {
                axMapControl2.Visible = false;
                this.panel11.BorderStyle = BorderStyle.None;
            }
        }
        #endregion
        #region 卫星数据或矢量数据的叠加
        //作者：代兴梅
        //描述：卫星图和矢量数据的分开加载

        //卫星底图是否加载
        bool isMoon = true;
        //矢量地图是否加载
        bool isVector = false;
        //加载初始化
        private void label1_Click(object sender, EventArgs e)
        {
            if (isMoon == false)
            {
                isMoon = true;
                this.axMapControl1.ClearLayers();
                IAddData maddData = new IAddData(this.axMapControl1);
                maddData.addData_Raster(ITiffPath);
                this.panel9.BorderStyle = BorderStyle.None;
                this.panel10.BorderStyle = BorderStyle.None;
                this.panel8.BorderStyle = BorderStyle.Fixed3D;
            }
            else
            {
                this.axMapControl1.ClearLayers();
                this.panel8.BorderStyle = BorderStyle.None;
                isMoon = false;
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {
            if (isVector == false)
            {
                isVector = true;
                this.axMapControl1.ClearLayers();
                IAddData maddData = new IAddData(this.axMapControl1);
                maddData.addData_Gdb(IGdbPath);
                this.panel8.BorderStyle = BorderStyle.None;
                this.panel10.BorderStyle = BorderStyle.None;
                this.panel9.BorderStyle = BorderStyle.Fixed3D;
            }
            else
            {
                this.axMapControl1.ClearLayers();
                this.panel9.BorderStyle = BorderStyle.None;
                isVector = false;
            }
        }
        private void label3_Click(object sender, EventArgs e)
        {
            if (this.panel10.BorderStyle == BorderStyle.Fixed3D)
            {
                this.axMapControl1.ClearLayers();
                this.panel9.BorderStyle = BorderStyle.None;
                isMoon = false;
                isVector = false;
            }
            if (this.panel10.BorderStyle == BorderStyle.None)
            {
                IAddData addData = new IAddData(this.axMapControl1);
                addData.addData_Raster(ITiffPath);
                addData.addData_Gdb(IGdbPath);
                this.panel10.BorderStyle = BorderStyle.Fixed3D;
                this.panel9.BorderStyle = BorderStyle.None;
                this.panel8.BorderStyle = BorderStyle.None;
                isMoon = true;
                isVector = true;
            }
        }
        #endregion
        #region 最短路径
        //几何网络
        private IGeometricNetwork mGeometricNetwork;
        //给定点的集合
        private IPointCollection mPointCollection;
        //获取给定点最近的Network元素
        private IPointToEID mPointToEID;

        //返回结果变量
        private IEnumNetEID mEnumNetEID_Junctions;
        private IEnumNetEID mEnumNetEID_Edges;
        private double mdblPathCost;
        private void SolvePath(string weightName)
        {
            //创建ITraceFlowSolverGEN
            ITraceFlowSolverGEN pTraceFlowSolverGEN = new TraceFlowSolverClass();
            INetSolver pNetSolver = pTraceFlowSolverGEN as INetSolver;
            //初始化用于路径计算的Network
            INetwork pNetWork = mGeometricNetwork.Network;
            pNetSolver.SourceNetwork = pNetWork;

            //获取分析经过的点的个数
            int intCount = mPointCollection.PointCount;
            if (intCount < 1)
                return;


            INetFlag pNetFlag;
            //用于存储路径计算得到的边
            IEdgeFlag[] pEdgeFlags = new IEdgeFlag[intCount];


            IPoint pEdgePoint = new PointClass();
            int intEdgeEID;
            IPoint pFoundEdgePoint;
            double dblEdgePercent;

            //用于获取几何网络元素的UserID, UserClassID,UserSubID
            INetElements pNetElements = pNetWork as INetElements;
            int intEdgeUserClassID;
            int intEdgeUserID;
            int intEdgeUserSubID;
            for (int i = 0; i < intCount; i++)
            {
                pNetFlag = new EdgeFlagClass();
                //获取用户点击点
                pEdgePoint = mPointCollection.get_Point(i);
                //获取距离用户点击点最近的边
                mPointToEID.GetNearestEdge(pEdgePoint, out intEdgeEID, out pFoundEdgePoint, out dblEdgePercent);
                if (intEdgeEID <= 0)
                    continue;
                //根据得到的边查询对应的几何网络中的元素UserID, UserClassID,UserSubID
                pNetElements.QueryIDs(intEdgeEID, esriElementType.esriETEdge,
                    out intEdgeUserClassID, out intEdgeUserID, out intEdgeUserSubID);
                if (intEdgeUserClassID <= 0 || intEdgeUserID <= 0)
                    continue;

                pNetFlag.UserClassID = intEdgeUserClassID;
                pNetFlag.UserID = intEdgeUserID;
                pNetFlag.UserSubID = intEdgeUserSubID;
                pEdgeFlags[i] = pNetFlag as IEdgeFlag;
            }
            //设置路径求解的边
            pTraceFlowSolverGEN.PutEdgeOrigins(ref pEdgeFlags);

            //路径计算权重
            INetSchema pNetSchema = pNetWork as INetSchema;
            INetWeight pNetWeight = pNetSchema.get_WeightByName(weightName);
            if (pNetWeight == null)
                return;

            //设置权重，这里双向的权重设为一致
            INetSolverWeights pNetSolverWeights = pTraceFlowSolverGEN as INetSolverWeights;
            pNetSolverWeights.ToFromEdgeWeight = pNetWeight;
            pNetSolverWeights.FromToEdgeWeight = pNetWeight;

            object[] arrResults = new object[intCount - 1];
            //执行路径计算
            pTraceFlowSolverGEN.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum,
                out mEnumNetEID_Junctions, out mEnumNetEID_Edges, intCount - 1, ref arrResults);

            //获取路径计算总代价（cost）
            mdblPathCost = 0;
            for (int i = 0; i < intCount - 1; i++)
                mdblPathCost += (double)arrResults[i];
        }
        private IPolyline PathToPolyLine()
        {
            IPolyline pPolyLine = new PolylineClass();
            IGeometryCollection pNewGeometryCollection = pPolyLine as IGeometryCollection;
            if (mEnumNetEID_Edges == null)
                return null;

            IEIDHelper pEIDHelper = new EIDHelperClass();
            //获取几何网络
            pEIDHelper.GeometricNetwork = mGeometricNetwork;
            //获取地图空间参考
            ISpatialReference pSpatialReference = this.axMapControl1.Map.SpatialReference;
            pEIDHelper.OutputSpatialReference = pSpatialReference;
            pEIDHelper.ReturnGeometries = true;
            //根据边的ID获取边的信息
            IEnumEIDInfo pEnumEIDInfo = pEIDHelper.CreateEnumEIDInfo(mEnumNetEID_Edges);
            int intCount = pEnumEIDInfo.Count;
            pEnumEIDInfo.Reset();

            IEIDInfo pEIDInfo;
            IGeometry pGeometry;
            for (int i = 0; i < intCount; i++)
            {
                pEIDInfo = pEnumEIDInfo.Next();
                //获取边的几何要素
                pGeometry = pEIDInfo.Geometry;
                pNewGeometryCollection.AddGeometryCollection((IGeometryCollection)pGeometry);
            }
            return pPolyLine;
        }
        #endregion
         INAContext pNAContext;
        private void Form1_Load(object sender, EventArgs e)
        {
            IGdbPath = Initialization.dGdbPath;
            ITiffPath = Initialization.dTiffPath;
            IAddData addData = new IAddData(this.axMapControl1);
            addData.addData_Raster(ITiffPath);
            addData.addData_Gdb(IGdbPath);
            this.panel10.BorderStyle = BorderStyle.Fixed3D;
            isMoon = true;
            isVector = true;
            //
            this.axMapControl2.Map = new MapClass();
            for (int i = 1; i <= this.axMapControl1.LayerCount; i++)
            {
                this.axMapControl2.AddLayer(this.axMapControl1.get_Layer(this.axMapControl1.LayerCount - i));
            }
            this.axMapControl2.Extent = this.axMapControl1.FullExtent;
            this.axMapControl2.Refresh();




            //try
            //{
            //    ////获取几何网络文件路径
            //    ////注意修改此路径为当前存储路径
            //    //string strPath = @"C:\Users\XGZ\Desktop\ISchool\ISchool\IData\ud.mdb";
            //    ////打开工作空间
            //    //IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactory();
            //    //IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(strPath, 0) as IFeatureWorkspace;
            //    ////获取要素数据集
            //    ////注意名称的设置要与上面创建保持一致
            //    //IFeatureDataset pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset("mLoad");

            //    ////获取network集合
            //    //INetworkCollection pNetWorkCollection = pFeatureDataset as INetworkCollection;
            //    ////获取network的数量,为零时返回
            //    //int intNetworkCount = pNetWorkCollection.GeometricNetworkCount;
            //    //if (intNetworkCount < 1)
            //    //    return;
            //    ////FeatureDataset可能包含多个network，我们获取指定的network
            //    ////注意network的名称的设置要与上面创建保持一致
            //    ////mGeometricNetwork = pNetWorkCollection.get_GeometricNetworkByName("high_net");

            //    ////将Network中的每个要素类作为一个图层加入地图控件
            //    //IFeatureClassContainer pFeatClsContainer = mGeometricNetwork as IFeatureClassContainer;
            //    ////获取要素类数量，为零时返回
            //    //int intFeatClsCount = pFeatClsContainer.ClassCount;
            //    //if (intFeatClsCount < 1)
            //    //    return;
            //    //IFeatureClass pFeatureClass;
            //    //IFeatureLayer pFeatureLayer;
            //    //for (int i = 0; i < intFeatClsCount; i++)
            //    //{
            //    //    //获取要素类
            //    //    pFeatureClass = pFeatClsContainer.get_Class(i);
            //    //    pFeatureLayer = new FeatureLayerClass();
            //    //    pFeatureLayer.FeatureClass = pFeatureClass;
            //    //    pFeatureLayer.Name = pFeatureClass.AliasName;
            //    //    //加入地图控件
            //    //    this.axMapControl1.AddLayer((ILayer)pFeatureLayer, 0);
            //    //}

            //    ////计算snap tolerance为图层最大宽度的1/100
            //    ////获取图层数量
            //    //int intLayerCount = this.axMapControl1.LayerCount;
            //    //IGeoDataset pGeoDataset;
            //    //IEnvelope pMaxEnvelope = new EnvelopeClass();
            //    //for (int i = 0; i < intLayerCount; i++)
            //    //{
            //    //    //获取图层
            //    //    pFeatureLayer = this.axMapControl1.get_Layer(i) as IFeatureLayer;
            //    //    pGeoDataset = pFeatureLayer as IGeoDataset;
            //    //    //通过Union获得较大图层范围
            //    //    pMaxEnvelope.Union(pGeoDataset.Extent);
            //    //}
            //    //double dblWidth = pMaxEnvelope.Width;
            //    //double dblHeight = pMaxEnvelope.Height;
            //    //double dblSnapTol;
            //    //if (dblHeight < dblWidth)
            //    //    dblSnapTol = dblWidth * 0.01;
            //    //else
            //    //    dblSnapTol = dblHeight * 0.01;

            //    ////设置源地图，几何网络以及捕捉容差
            //    //mPointToEID = new PointToEIDClass();
            //    //mPointToEID.SourceMap = this.axMapControl1.Map;
            //    //mPointToEID.GeometricNetwork = mGeometricNetwork;
            //    //mPointToEID.SnapTolerance = dblSnapTol;

            //    IFeatureWorkspace featureWorkspace = null;
            //    INetworkDataset networkDataset = null;
            //    string strGDB = @"C:\Users\XGZ\Desktop\ISchool\ISchool\IData\地理数据库.gdb";
            //    IWorkspace workspace = OpenWorkspace(strGDB);
            //    networkDataset = OpenNetworkDataset(workspace, "bestLoad", "bestLoad_ND");
            //    featureWorkspace = workspace as IFeatureWorkspace;
            //    CreateSolverContext(networkDataset);
            //}
            //catch (Exception ex)
            //{
                
            //}

        }
        #region 属性查询
        private void label21_Click_1(object sender, EventArgs e)
        {
            panel050.Visible = true;
            panel052.Visible = false;
            panel053.Visible = false;
            this.comboBox01.Items.Clear();
            pHookHelper.Hook = this.axMapControl1.Object;
            FeatureLayerLoad();
        }
        public IHookHelper pHookHelper = new HookHelperClass();
        public void FeatureLayerLoad()
        {
            //判断控件对象是否为空
            if (pHookHelper == null || pHookHelper.Hook == null || pHookHelper.FocusMap.LayerCount == 0)
            {
                return;
            }
            IEnumLayer layers = GetLayers();
            layers.Reset();
            ILayer layer = null;
            while ((layer = layers.Next()) != null)
            {
                this.comboBox01.Items.Add(layer.Name);
            }
            if (this.comboBox01.Items.Count > 0)
            {
                this.comboBox01.SelectedIndex = 0;
            }
        }
        private IEnumLayer GetLayers()
        {
            UID uid = new UIDClass();
            uid.Value = "{40A9E885-5533-11d0-98BE-00805F7CED21}";
            IEnumLayer layers = pHookHelper.FocusMap.get_Layers(uid, true);
            return layers;
        }
        private void button03_Click_1(object sender, EventArgs e)
        {
            if (comboBox04.Text == "点查询")
            {
                mMouseFlag = 1;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;

            }
            else if (comboBox04.Text == "线查询")
            {
                mMouseFlag = 2;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
            }
            else if (comboBox04.Text == "面查询")
            {
                mMouseFlag = 3;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
            }
            pHookHelper.Hook = this.axMapControl1.Object;
        }

        private void button01_Click_1(object sender, EventArgs e)
        {
            this.axMapControl1.Map.ClearSelection();
            IFeatureLayer pFeatureLayer = axMapControl1.get_Layer(comboBox01.SelectedIndex) as IFeatureLayer;
            IClone pClone = pFeatureLayer.FeatureClass.Fields as IClone;
            IFields pFields = pClone.Clone() as IFields;
            if (pFeatureLayer == null)
            {
                MessageBox.Show("请输入图层！", "提示");
                return;
            }
            IQueryFilter pQueryFilter = new QueryFilter();
            pQueryFilter.WhereClause = "OBJECTID" + "=" + textBox01.Text;
            pQueryFilter.WhereClause = "name like '%" + textBox01.Text + "%'";
            try
            {

                IFeatureCursor pFeatureCursor = pFeatureLayer.FeatureClass.Search(pQueryFilter, false);
                IFeature pFeature = pFeatureCursor.NextFeature();

                if (pFeature != null)
                {


                    IPoint point = pFeature.Shape as IPoint;
                    this.axMapControl1.CenterAt(point);
                    this.axMapControl1.Map.SelectFeature(pFeatureLayer, pFeature);
                    //this.axMapControl1.FlashShape(pFeature.Shape, 3, 192, null);
                    //this.axMapControl1.TrackLine();
                    //this.axMapControl1.TrackRectangle();
                    //this.axMapControl1.ActiveView.Refresh();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        #region 缓冲区查询

        private void label20_Click_1(object sender, EventArgs e)
        {
            this.panel050.Visible = true;
            this.panel053.Visible = true;

            panel052.Visible = false;
        }
        //根据屏幕像素来计算实际的地理距离
        public double ConvertPixelToMapUnits(IActiveView activeView, double pixelUnits)
        {
            double realWorldDiaplayExtent; int pixelExtent; double sizeOfOnePixel; double mapUnits;
            //获取设备中视图显示宽度，即像素个数 
            pixelExtent = activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().right - activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().left;//获取地图坐标系中地图显示范围             
            realWorldDiaplayExtent = activeView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width; //每个像素大小代表的实际距离 
            sizeOfOnePixel = realWorldDiaplayExtent / pixelExtent; //地理距离 
            mapUnits = pixelUnits * sizeOfOnePixel;
            return mapUnits;
        }


        //查询的函数
        private void QuerySpatial(AxMapControl mapControl, IGeometry geometry)
        {

            IEnumLayer layers = GetLayers();


            //string strNames = null;
            for (int i = 0; layers.Next() != null; i++)
            {
                mapControl.Map.ClearSelection();
                IFeatureLayer pFeatureLayer;
                IFeatureClass pFeatureClass;
                pFeatureLayer = pHookHelper.FocusMap.get_Layer(i) as IFeatureLayer;

                pFeatureClass = pFeatureLayer.FeatureClass;
                if (pFeatureClass == null) return;
                //初始化空间过滤器
                ISpatialFilter pSpatialFilter;
                pSpatialFilter = new SpatialFilterClass();
                pSpatialFilter.Geometry = geometry;
                //根据图层类型选择缓冲方式
                switch (pFeatureClass.ShapeType)
                {
                    case esriGeometryType.esriGeometryPoint:
                        pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                        break;
                    case esriGeometryType.esriGeometryPolyline:
                        pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;
                        break;
                    case esriGeometryType.esriGeometryPolygon:
                        pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        break;
                }
                //定义空间过滤器的空间字段
                pSpatialFilter.GeometryField = pFeatureClass.ShapeFieldName;
                IQueryFilter pQueryFilter;
                IFeatureCursor pFeatureCursor;
                IFeature pFeature;
                pQueryFilter = pSpatialFilter as IQueryFilter;
                pFeatureCursor = pFeatureLayer.Search(pQueryFilter, true);
                pFeature = pFeatureCursor.NextFeature();

                while (pFeature != null)
                {
                    ////选择指定要素
                    //fieldIndex = pFeature.Fields.FindField(fieldName);
                    ////获取要素名称
                    //strNames = strNames + pFeature.get_Value(fieldIndex) + ";";
                    mapControl.Map.SelectFeature((ILayer)pFeatureLayer, pFeature);
                    mapControl.FlashShape(pFeature.Shape, 3, 192, null);
                    mapControl.ActiveView.Refresh();
                    pFeature = pFeatureCursor.NextFeature();
                }


            }
            //return strNames;
        }
        int mMouseFlag;
        #endregion
        #region 菜单栏的移动
        private void panel4_MouseDown(object sender, MouseEventArgs e)
        {
            this.panel4.setVisiblePanel(this.panel27);
        }
        private void panel18_MouseDown(object sender, MouseEventArgs e)
        {
            this.panel18.setVisiblePanel(this.panel19);
        }
        #endregion
        private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e)
        {
            if (isShort == true&&e.button==1)
            {
                if (flagbool != true)
                    return;
                IPoint pPoint1 = this.axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                if (m_PointCollection == null)
                {
                    m_PointCollection = new MultipointClass();
                }
                pPoint1 = m_ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                object o = Type.Missing;
                m_PointCollection.AddPoint(pPoint1, ref o, ref o);

                IElement element;
                ITextElement textelement = new TextElementClass();
                element = textelement as IElement;
                clickcount++;
                textelement.Text = clickcount.ToString();
                element.Geometry = m_ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                m_GraphicsContainer.AddElement(element, 0);
                m_ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
            if (isShort == true && e.button == 2)
            {
                isShort = false;
                this.label37.Parent = this.axMapControl1;
                this.label37.BringToFront();
                this.label37.Visible = true;
                this.label37.Location = new System.Drawing.Point(e.x, e.y);
            }

            if (e.button == 2)
            {
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerArrow;
            }

            //放大操作
            if (mZoomIn != null && e.button == 1)
            {
                mZoomIn.OnMouseDown(e.button, e.shift, e.x, e.y);
            }
           

            //距离量算
            if (isCalCulationDistance == true && e.button == 1)
            {
                listBox1.Location = new System.Drawing.Point(e.x, e.y);
                listBox1.Visible = true;
                listBox1.Parent = this.axMapControl1;
                ISpaceCalCulation.Idistance(e.x, e.y);
            }
            if (isCalCulationDistance == true && e.button == 2)
            {
                isCalCulationDistance = false;
                this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
            if (isCalCulationArea == true && e.button == 1)
            {
                ISpaceCalCulation.IArea(e.x, e.y);
            }
            if (isCalCulationArea == true && e.button == 2)
            {
                isCalCulationArea = false;
            }




            if (mMouseFlag == 1)
            {

                //string strFieldName = "OBJECTID";
                IActiveView pActiveView;
                IPoint pPoint;
                double length;
                pActiveView = this.axMapControl1.ActiveView;
                pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                length = ConvertPixelToMapUnits(pActiveView, Convert.ToDouble(textBox04.Text));
                ITopologicalOperator pTopologicalOperator;
                IGeometry pGeoBuffer;
                pTopologicalOperator = pPoint as ITopologicalOperator;
                pGeoBuffer = pTopologicalOperator.Buffer(length);
                QuerySpatial(this.axMapControl1, pGeoBuffer);

            }
            else if (mMouseFlag == 2)
            {



                ISimpleLineSymbol psl = new SimpleLineSymbolClass();
                RgbColor rgbcolor = new RgbColorClass();
                rgbcolor.Red = 192;
                rgbcolor.Blue = 0;
                rgbcolor.Green = 0;
                psl.Color = rgbcolor;
                IGeometry pgeo;
                pgeo = axMapControl1.TrackLine();
                QuerySpatial(this.axMapControl1, pgeo);


            }
            else if (mMouseFlag == 3)
            {

                QuerySpatial(this.axMapControl1, this.axMapControl1.TrackCircle());

            }
            ////记录鼠标点击的点
            //IPoint pNewPoint = new PointClass();
            //pNewPoint.PutCoords(e.mapX, e.mapY);

            //if (mPointCollection == null)
            //    mPointCollection = new MultipointClass();
            ////添加点，before和after标记添加点的索引，这里不定义
            //object before = Type.Missing;
            //object after = Type.Missing;
            //mPointCollection.AddPoint(pNewPoint, ref before, ref after);

        }
        #region 地图的放大、缩小和复位
        //作者：郭菲
        //描述：点击放大过后，可以支持拉框放大，
        private ZoomOutORIn mZoomIn = null;
        private RoomOutORIn.InOrOut isBig =RoomOutORIn.InOrOut.Defualt;
        private void label10_Click(object sender, EventArgs e)
        {

            isBig = RoomOutORIn.InOrOut.In;
            
            //初始化 
            mZoomIn = new ZoomOutORIn();             
            //与MapControl的关联 
            mZoomIn.OnCreate(this.axMapControl1.Object);
            NotBig(isBig);
        }
        //根据操作类型设置鼠标类型
        private void NotBig(RoomOutORIn.InOrOut dd)
        {
            if (dd == RoomOutORIn.InOrOut.In)
            {
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPageZoomIn;
            }
            if (dd == RoomOutORIn.InOrOut.Out)
            {
                this.mZoomIn = null;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPageZoomOut;
            }
            if (dd == RoomOutORIn.InOrOut.Defualt)
            {
                this.mZoomIn = null;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;
            }
            if (dd == RoomOutORIn.InOrOut.Pan)
            {
                this.mZoomIn = null;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;
            }
        }
        private void label11_Click(object sender, EventArgs e)
        {
            isBig = RoomOutORIn.InOrOut.Out;
            NotBig(isBig);
            RoomOutORIn mroom = new RoomOutORIn(this.axMapControl1, RoomOutORIn.InOrOut.Out);
        }
        private void label13_Click(object sender, EventArgs e)
        {
            isBig = RoomOutORIn.InOrOut.Defualt;
            NotBig(isBig);
            RoomOutORIn mroom = new RoomOutORIn(this.axMapControl1, RoomOutORIn.InOrOut.Defualt);
        }
        //平移
        private void label12_Click(object sender, EventArgs e)
        {
            isBig = RoomOutORIn.InOrOut.Pan;
            NotBig(isBig);
            RoomOutORIn d = new RoomOutORIn(this.axMapControl1, RoomOutORIn.InOrOut.Pan);
        }
        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            //放大操作
            if (mZoomIn != null&&e.button==(int)MouseButtons.Left)
            {
                mZoomIn.OnMouseMove(e.button, e.shift, e.x, e.y);
            }
            this.listBox1.Visible = false;
        }

        private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {
            //放大操作
            if (mZoomIn != null && e.button ==1)
            {
                mZoomIn.OnMouseUp(e.button, e.shift, e.x, e.y);
            }
            //缩小操作
            if (isBig == RoomOutORIn.InOrOut.Out && e.button ==1)
            {
                RoomOutORIn d = new RoomOutORIn(this.axMapControl1, RoomOutORIn.InOrOut.Out);
            }
        }


        #endregion

        #region 菜单栏、工具条伸缩
        private bool paneltoolisout = false;
        private void label9_Click(object sender, EventArgs e)
        {
            this.panel19.Parent = this.axMapControl1;
            this.panel19.BringToFront();
            this.panel19.setIPanelLoction(this.panel15.Location.X, this.panel15.Location.Y + this.panel15.Height - 1);
            this.panel19.Width = this.panel5.Width;
            this.Refresh();
        }
        //菜单栏下拉
        private void label6_Click(object sender, EventArgs e)
        {
            this.panel27.Parent = this.axMapControl1;
            this.panel27.BringToFront();
            this.panel27.setIPanelLoction(this.panel3.Location.X, this.panel3.Location.Y + this.panel3.Height - 1);
            this.panel27.Width = this.panel3.Width;
            this.Refresh();
        }
        private bool labelIsOut = false;
        private void label18_Click(object sender, EventArgs e)
        {
            this.panel27.setVisiblePanel(this.panel35);
            //初次直接显示
            if (labelIsOut == false)
            {
                //指定父容器
                this.panel35.Parent = this.axMapControl1;
                //最顶层
                this.panel35.BringToFront();
                //获取出现的坐标值
                int x = this.panel27.Location.X + this.panel28.Location.X + this.panel28.Width;
                int y = this.panel27.Location.Y + this.panel31.Location.Y;
                //获取位置
                this.panel35.setIPanelLoction(x, y);
                labelIsOut = true;
            }
            else
            {
                //非首次，则先将所有显示出来的隐藏
                this.panel35.Visible = false;
                this.panel37.Visible = false;
                this.panel45.Visible = false;
                //同上
                this.panel35.Parent = this.axMapControl1;
                this.panel35.BringToFront();
                int x = this.panel27.Location.X + this.panel28.Location.X + this.panel28.Width;
                int y = this.panel27.Location.Y + this.panel31.Location.Y;
                this.panel35.setIPanelLoction(x, y);
            }
        }
        private void label17_Click(object sender, EventArgs e)
        {
            this.panel27.setVisiblePanel(this.panel37);
            //同上
            if (labelIsOut == false)
            {
                this.panel37.Parent = this.axMapControl1;
                this.panel37.BringToFront();
                int x = this.panel27.Location.X + this.panel28.Location.X + this.panel28.Width;
                int y = this.panel27.Location.Y + this.panel30.Location.Y;
                this.panel37.setIPanelLoction(x, y);
                labelIsOut = true;
            }
            else
            {
                this.panel35.Visible = false;
                this.panel37.Visible = false;
                this.panel45.Visible = false;
                this.panel37.Parent = this.axMapControl1;
                this.panel37.BringToFront();
                int x = this.panel27.Location.X + this.panel28.Location.X + this.panel28.Width;
                int y = this.panel27.Location.Y + this.panel30.Location.Y;
                this.panel37.setIPanelLoction(x, y);
            }
        }

        private void label16_Click(object sender, EventArgs e)
        {
            this.panel27.setVisiblePanel(this.panel45);
            //同上
            if (labelIsOut == false)
            {
                this.panel45.Parent = this.axMapControl1;
                this.panel45.BringToFront();
                int x = this.panel27.Location.X + this.panel28.Location.X + this.panel28.Width;
                int y = this.panel27.Location.Y + this.panel29.Location.Y;
                this.panel45.setIPanelLoction(x, y);
                labelIsOut = true;
            }
            else
            {
                this.panel35.Visible = false;
                this.panel37.Visible = false;
                this.panel45.Visible = false;
                this.panel45.Parent = this.axMapControl1;
                this.panel45.BringToFront();
                int x = this.panel27.Location.X + this.panel28.Location.X + this.panel28.Width;
                int y = this.panel27.Location.Y + this.panel29.Location.Y;
                this.panel45.setIPanelLoction(x, y);
            }
        }
        #endregion
        #region 侧边栏
        private void label5_Click(object sender, EventArgs e)
        {

        }
        #endregion
        #region 量算
        //作者：田桂芳
        //描述：距离量算与面积测算
        private bool isCalCulationDistance = false;
        private bool isCalCulationArea = false;
        SpaceCalCulation ISpaceCalCulation;
        private void label14_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            ISpaceCalCulation = new SpaceCalCulation(this.axMapControl1, this.listBox1);
            isCalCulationDistance = true;
            MessageBox.Show("现在你可以单击左键开始测距，单击右键结束");
        }
        private void label15_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            isCalCulationArea = true;
            ISpaceCalCulation = new SpaceCalCulation(this.axMapControl1, this.listBox1);
            MessageBox.Show("现在你可以单击左键开始面积测量（点至少要3个及以上），单击右键结束");
        }
        #endregion
        #region 缓冲区分析
        //作者：宋翔
        //描述：执行图层的缓冲区分析
        //缓冲区分析进入
        private void label27_Click(object sender, EventArgs e)
        {
            this.panel12.Visible = true;
        }
        IBuffer tBuffer;
        private void panel12_VisibleChanged(object sender, EventArgs e)
        {
            //先清空combox
            this.cboLayers.Items.Clear();
            //初始化，绑定操作MapControl
            tBuffer = new IBuffer(this.axMapControl1.Object);
            //绑定容器
            tBuffer.setComboBoxLabel(this.cboLayers);
            //加载文件名到combox中
            tBuffer.FeatureLayerLoad();

            txtOutputPath.Text = tBuffer.strOutputPath;
            //获取地图的单位并设置到combox中去
            int units = Convert.ToInt32(this.axMapControl1.MapUnits);
            cboUnits.SelectedIndex = units;
        }
        private void cboLayers_TextChanged(object sender, EventArgs e)
        {
            //设置新的文件名
            txtOutputPath.Text = tBuffer.strOutputPath;
        }
        private void btnBuffer_Click(object sender, EventArgs e)
        {
            //设置缓冲区距离参数
            tBuffer.setDistance(Double.Parse(txtBufferDistance.Text.ToString()), (string)cboUnits.SelectedItem);
            //执行缓冲区
            tBuffer.mBufferDo();
            //获取输出shp所在的文件夹
            string strFilePath = System.IO.Path.GetDirectoryName(txtOutputPath.Text);
            //获取输出shp的文件名
            string streFileName = System.IO.Path.GetFileName(txtOutputPath.Text);
            //添加缓冲区shp文件
            this.axMapControl1.AddShapeFile(strFilePath, streFileName);
            this.axMapControl1.Extent = this.axMapControl1.FullExtent;
        }
        private void btnOutputLayer_Click(object sender, EventArgs e)
        {
            //获取另存名
            tBuffer.otherFeaturePath();
            txtOutputPath.Text = tBuffer.strOutputPath;
        }
        #endregion
        #region （额外）添加数据
        //作者：代兴梅
        //描述：额外的添加数据

        IAddData iAddData;
        private void label23_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openfileDialog = new OpenFileDialog();
            openfileDialog.Title = "添加数据";
            openfileDialog.Filter = "矢量文件（*.shp）|*.shp|栅格文件（*.bmp,*jpg,*.img,*.tif）|*.bmp;*.jpg;*.img;*.tif|专题图数据（*.mdb）|*.mdb";
            openfileDialog.Multiselect = true;
            iAddData = new IAddData(this.axMapControl1);
            if (openfileDialog.ShowDialog() == DialogResult.OK)
            {
                string datatype = System.IO.Path.GetExtension(openfileDialog.FileName);
                if (datatype == ".shp")
                {
                    iAddData.addData_Shp(openfileDialog.FileName);
                }
                else if (datatype == ".mdb")
                {
                    iAddData.addData_Mdb(openfileDialog.FileName);
                }
                else if (datatype == ".tif" || datatype == ".jpg" || datatype == ".bmp" || datatype == ".img")
                {
                    iAddData.addData_Raster(openfileDialog.FileName);
                }
                else
                {

                }
            }
        }
        //加载GDB文件
        private void label22_Click(object sender, EventArgs e)
        {
            string gdbPath = "";
            FolderBrowserDialog testMyFolder = new FolderBrowserDialog();
            if (testMyFolder.ShowDialog() == DialogResult.OK)
            {
                gdbPath = testMyFolder.SelectedPath;
            }
            iAddData = new IAddData(this.axMapControl1);
            iAddData.addData_Gdb(gdbPath);
        }
        //打开地图文档文件
        
        private void label24_Click(object sender, EventArgs e)
        {
            IOpenDocment mOpenDocment = new IOpenDocment(this.axMapControl1);
            mOpenDocment.mOpen();
        }
        //存储
        ISaveOrSaveAs iSaveOrSaveAs;
        private void label30_Click(object sender, EventArgs e)
        {
            iSaveOrSaveAs = new ISaveOrSaveAs(this.axMapControl1);
            iSaveOrSaveAs.mSave();
        }
        //另存为
        private void label29_Click(object sender, EventArgs e)
        {
            iSaveOrSaveAs = new ISaveOrSaveAs(this.axMapControl1);
            iSaveOrSaveAs.mSaveAs();
        }

        //保存并退出
        private void label28_Click(object sender, EventArgs e)
        {
            iSaveOrSaveAs = new ISaveOrSaveAs(this.axMapControl1);
            iSaveOrSaveAs.mSave();
            Application.Exit();
        }
        #endregion



        #region 鹰眼的实现
       //作者：郭菲
        //描述：提供鹰眼视图
        private void axMapControl2_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (this.axMapControl2.Map.LayerCount != 0)
            {
                // 按下鼠标左键移动矩形框
                if (e.button == 1)
                {
                    IPoint pPoint = new PointClass();
                    pPoint.PutCoords(e.mapX, e.mapY);
                    IEnvelope pEnvelope = this.axMapControl1.Extent;
                    pEnvelope.CenterAt(pPoint);
                    this.axMapControl1.Extent = pEnvelope;
                    this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }
                // 按下鼠标右键绘制矩形框
                if (e.button == 2)
                {
                    IEnvelope pEnvelop = this.axMapControl2.TrackRectangle();
                    this.axMapControl1.Extent = pEnvelop;
                    this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }

            }
        }

        private void axMapControl2_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            if (e.button != 1) return;
            IPoint pPoint = new PointClass();
            pPoint.PutCoords(e.mapX, e.mapY);
            this.axMapControl1.CenterAt(pPoint);
            this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        
        }
        private void axMapControl2_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            //创建鹰眼中线框
            IEnvelope pEnv = (IEnvelope)e.newEnvelope;
            IRectangleElement pRectangleEle = new RectangleElementClass();
            IElement pEle = pRectangleEle as IElement;
            pEle.Geometry = pEnv;

            //设置线框的边线对象，包括颜色和线宽
            IRgbColor pColor = new RgbColorClass();
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 255;
            //产生一个线性符号对象
            ILineSymbol pOutLine = new SimpleLineSymbolClass();
            pOutLine.Width = 2;
            pOutLine.Color = pColor;
            //设置颜色属性
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 0;
            //设置线框填充符号的属性
            IFillSymbol pFillSymbol = new SimpleFillSymbolClass();
            pFillSymbol.Color = pColor;
            IFillShapeElement pFillShapeEle = pEle as IFillShapeElement;
            pFillShapeEle.Symbol = pFillSymbol;
            IGraphicsContainer pGra = this.axMapControl2.Map as IGraphicsContainer;
            IActiveView pAv = pGra as IActiveView;
            //绘制前清楚 axMapControl1 中的任何图形元素
            pGra.DeleteAllElements();
            //鹰眼中添加线框
            pGra.AddElement((IElement)pFillShapeEle, 0);
            pAv.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            this.axMapControl2.Map = new MapClass();
            for (int i = 1; i <= this.axMapControl1.LayerCount; i++)
            {
                this.axMapControl2.AddLayer(this.axMapControl1.get_Layer(this.axMapControl1.LayerCount - i));
            }
            this.axMapControl2.Extent = this.axMapControl1.FullExtent;
            this.axMapControl2.Refresh();
        }
        #endregion
        #region 叠置分析
        IOverlay iOverLay;
        //作者：向桂泽
        //描述：提供叠置分析
        private void panel56_VisibleChanged(object sender, EventArgs e)
        {
            //控件关联
            iOverLay = new IOverlay(this.axMapControl1.Object);
            iOverLay.getLayer(comboBox1);
            //listview初始参数设置
            listView1.Clear();
            listView1.View = View.Details;
            listView1.GridLines = true;
            listView1.FullRowSelect = true;
            listView1.Columns.Add("num", "编号");
            listView1.Columns.Add("layername", "图层名称");
            listView1.Columns["num"].Width = -2;
            listView1.Columns["layername"].Width = -2;
        }
        private void button7_Click(object sender, EventArgs e)
        {
            bool isAdd = true;
            //listView中是否存在该矢量图层
            if (listView1.Items.Count > 0 && comboBox1.SelectedItem.ToString() != string.Empty)
            {
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    if (listView1.Items[i].SubItems[1].Text == comboBox1.SelectedItem.ToString())
                    {
                        isAdd = false;
                        listView1.Items[i].Selected = true;
                        listView1.Items[i].EnsureVisible();
                        MessageBox.Show("已有该图层");
                    }
                    else
                    {
                        isAdd = true;
                    }
                }
            }
            //添加许可为真，执行添加
            if (isAdd == true)
            {
                ListViewItem mListView = new ListViewItem();
                int j = listView1.Items.Count;
                mListView.SubItems[0].Text = (j + 1).ToString();
                mListView.SubItems.Add(comboBox1.SelectedItem.ToString());
                listView1.Items.Add(mListView);
            }
        }
        private void button6_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems != null)
            {
                int j = listView1.SelectedIndices.Count;
                int i = listView1.SelectedIndices[0];
                listView1.Items.RemoveAt(i);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            int i = listView1.SelectedIndices[0];
            if (i >= 1)
            {
                ListViewItem mItem = new ListViewItem();
                mItem = listView1.SelectedItems[0];
                listView1.Items[i - 1] = mItem;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            listView1.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            iOverLay.otherFeaturePath();
            textBox1.Text = iOverLay.strOutputPath;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string[] name = new string[listView1.Items.Count];
            //获取图层列表
            if (listView1.Items.Count >= 2)
            {
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    name[i] = listView1.Items[i].SubItems[1].Text;
                }
            }
            else
            {
                MessageBox.Show("叠置至少需要两个图层，请重新添加图层");
            }

            if (iOverLay.getFeatureLayer(name))
            {
                iOverLay.mOverLay();
            }
        }
        #endregion

        private void panel58_Paint(object sender, PaintEventArgs e)
        {
            ////旋转显示文字
            //Graphics g = e.Graphics;
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            ////平移Graphics对象到窗体中心
            //g.TranslateTransform(this.Parent.Width / 2, this.Parent.Height / 2);
            ////设置Graphics对象的输出角度
            //g.RotateTransform(180);
            ////设置文字填充颜色
            //Brush brush = Brushes.DarkViolet;
            ////旋转显示文字
            //g.DrawString("哈哈哈哈", new Font("Lucida Console", 11f), brush, 0, 0);
            ////恢复全局变换矩阵
            //g.ResetTransform();
        }

        private void label35_Click(object sender, EventArgs e)
        {
            this.Parent.Parent.Visible = false;
        }

        private void label26_Click(object sender, EventArgs e)
        {
            this.panel56.Visible = true;
        }


        private void label9_Click(object sender, MouseEventArgs e)
        {

        }
        int j = 0;
        private void axMapControl1_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e)
        {
            if(j==0){
                startIpoint = new PointClass();
                //获取地图的控件坐标体系
                startIpoint.SpatialReference = this.axMapControl1.Map.SpatialReference;
                //屏幕点转地图坐标
                startIpoint = this.axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                j++;
            }
            if(j==1)
            {
                endIpoint = new PointClass();
                //获取地图的控件坐标体系
                endIpoint.SpatialReference = this.axMapControl1.Map.SpatialReference;
                //屏幕点转地图坐标
                endIpoint = this.axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                j++;
            }
            try
            {
                //路径计算
                //注意权重名称与设置保持一致
                SolvePath("LENGTH");
                //路径转换为几何要素
                IPolyline pPolyLineResult = PathToPolyLine();
                //获取屏幕显示
                IActiveView pActiveView = this.axMapControl1.ActiveView;
                IScreenDisplay pScreenDisplay = pActiveView.ScreenDisplay;
                //设置显示符号
                ILineSymbol pLineSymbol = new CartographicLineSymbolClass();
                IRgbColor pColor = new RgbColorClass();
                pColor.Red = 255;
                pColor.Green = 0;
                pColor.Blue = 0;
                //设置线宽
                pLineSymbol.Width = 4;
                //设置颜色
                pLineSymbol.Color = pColor as IColor;
                //绘制线型符号
                pScreenDisplay.StartDrawing(0, 0);
                pScreenDisplay.SetSymbol((ISymbol)pLineSymbol);
                pScreenDisplay.DrawPolyline(pPolyLineResult);
                pScreenDisplay.FinishDrawing();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("路径分析出现错误:" + "\r\n" + ex.Message);
            }
            //点集设为空
            mPointCollection = null;

        }
        #region 移出范围则工具条，菜单栏隐藏

        private INAContext m_NAContext;

        private IPoint startIpoint;
        private IPoint endIpoint;

        public IWorkspace OpenWorkspace(string strGDBName)
        {
            // As Workspace Factories are Singleton objects, they must be instantiated with the Activator
            var workspaceFactory = System.Activator.CreateInstance(System.Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory")) as ESRI.ArcGIS.Geodatabase.IWorkspaceFactory;

            if (!System.IO.Directory.Exists(strGDBName))
            {
                MessageBox.Show("The workspace: " + strGDBName + " does not exist", "Workspace Error");
                return null;
            }

            IWorkspace workspace = null;
            try
            {
                workspace = workspaceFactory.OpenFromFile(strGDBName, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Opening workspace failed: " + ex.Message, "Workspace Error");
            }

            return workspace;
        }
        public INetworkDataset OpenNetworkDataset(IWorkspace workspace, string featureDatasetName, string strNDSName)
        {
            // Obtain the dataset container from the workspace
            var featureWorkspace = workspace as IFeatureWorkspace;
            ESRI.ArcGIS.Geodatabase.IFeatureDataset featureDataset = featureWorkspace.OpenFeatureDataset(featureDatasetName);
             var featureDatasetExtensionContainer = featureDataset as ESRI.ArcGIS.Geodatabase.IFeatureDatasetExtensionContainer;
            ESRI.ArcGIS.Geodatabase.IFeatureDatasetExtension featureDatasetExtension = featureDatasetExtensionContainer.FindExtension(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTNetworkDataset);
            var datasetContainer3 = featureDatasetExtension as ESRI.ArcGIS.Geodatabase.IDatasetContainer3;

            // Use the container to open the network dataset.
            ESRI.ArcGIS.Geodatabase.IDataset dataset = datasetContainer3.get_DatasetByName(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTNetworkDataset, strNDSName);
            return dataset as ESRI.ArcGIS.Geodatabase.INetworkDataset;
        }
        public IDENetworkDataset GetDENetworkDataset(INetworkDataset networkDataset)
        {
            // Cast from the network dataset to the DatasetComponent
            IDatasetComponent dsComponent = networkDataset as IDatasetComponent;

            // Get the data element
            return dsComponent.DataElement as IDENetworkDataset;
        }
        public void CreateSolverContext(INetworkDataset networkDataset)
        {
            if (networkDataset == null) return;

            //Get the Data Element
            IDENetworkDataset deNDS = GetDENetworkDataset(networkDataset);

            INASolver naSolver = new NAClosestFacilitySolver();
            m_NAContext = naSolver.CreateContext(deNDS, naSolver.Name);
            ((INAContextEdit)m_NAContext).Bind(networkDataset, new GPMessagesClass());
        }

        public void LoadNANetworkLocations(string strNAClassName, IFeatureClass inputFC, double maxSnapTolerance)
        {
            INamedSet classes = m_NAContext.NAClasses;
            INAClass naClass = classes.get_ItemByName(strNAClassName) as INAClass;

            // delete existing Locations except if that a barriers
            naClass.DeleteAllRows();

            // Create a NAClassLoader and set the snap tolerance (meters unit)
            INAClassLoader classLoader = new NAClassLoader();
            classLoader.Locator = m_NAContext.Locator;
            if (maxSnapTolerance > 0) ((INALocator3)classLoader.Locator).MaxSnapTolerance = maxSnapTolerance;
            classLoader.NAClass = naClass;

            //Create field map to automatically map fields from input class to NAClass
            INAClassFieldMap fieldMap = new NAClassFieldMapClass();
            fieldMap.CreateMapping(naClass.ClassDefinition, inputFC.Fields);
            classLoader.FieldMap = fieldMap;

            // Avoid loading network locations onto non-traversable portions of elements
            INALocator3 locator = m_NAContext.Locator as INALocator3;
            locator.ExcludeRestrictedElements = true;
            locator.CacheRestrictedElements(m_NAContext);

            //Load Network Locations
            int rowsIn = 0;
            int rowsLocated = 0;
            IFeatureCursor featureCursor = inputFC.Search(null, true);
            classLoader.Load((ICursor)featureCursor, null, ref rowsIn, ref rowsLocated);

            //Message all of the network analysis agents that the analysis context has changed
            ((INAContextEdit)m_NAContext).ContextChanged();
        }
        public void CreateFeature(IFeatureClass featureClass, IPointCollection PointCollection)
        {
            // Ensure the feature class contains points.
            if (featureClass.ShapeType != esriGeometryType.esriGeometryPoint)
            {
                return;
            }

            // Build the feature.
            for (int i = 0; i < PointCollection.PointCount; i++)
            {
                IFeature feature = featureClass.CreateFeature();
                feature.Shape = PointCollection.get_Point(i);


                // Apply the appropriate subtype to the feature.
                ISubtypes subtypes = (ISubtypes)featureClass;
                IRowSubtypes rowSubtypes = (IRowSubtypes)feature;
                if (subtypes.HasSubtype)
                {
                    // In this example, the value of 3 represents the Cross subtype.
                    rowSubtypes.SubtypeCode = 3;
                }

                // Initialize any default values the feature has.
                rowSubtypes.InitDefaultValues();

                // Update the value on a string field that indicates who installed the feature.
                //int contractorFieldIndex = featureClass.FindField("CONTRACTOR");
                //feature.set_Value(contractorFieldIndex, "K Johnston");

                // Commit the new feature to the geodatabase.
                feature.Store();
            }
        }
        #endregion

        #region 地理网络分析最短路径
        //作者：向桂泽
        #region 全局变量

        private IPolyline m_Polyline;
        private IMap m_Map;
        private bool flagbool;//标记是否获得网络工作图层的变量
        private int clickcount;//标记点的个数

        private IGraphicsContainer m_GraphicsContainer;
        private static IGeometricNetwork m_GeometricNetwork;
        private IPointCollection m_PointCollection;
        private IPointToEID m_PointToEID;
        private IEnumNetEID m_EnumNetEID_Junctions;
        private IEnumNetEID m_EnumNetEID_Edges;
        private IActiveView m_ActiveView;
        private double m_PathCost;

        #endregion
        //可以选择图层进行最短路径分析
        //  获取起始点
        private bool isShort=false;
        private void label19_Click(object sender, EventArgs e)
        {
            isShort = true;
            m_Map = this.axMapControl1.ActiveView.FocusMap;
            m_ActiveView = this.axMapControl1.ActiveView;
            m_GraphicsContainer = m_Map as IGraphicsContainer;
            if (m_Map.LayerCount == 0) return;
            ILayer pLayer = m_Map.get_Layer(0);

            IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
            IFeatureDataset pFeatureDateset = pFeatureLayer.FeatureClass.FeatureDataset;
            Open_FeatureDataset_Network(pFeatureDateset);
            flagbool = true;
            clickcount = 0;
            m_GraphicsContainer.DeleteAllElements();
            //this.mTool = "flag";
            axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }
        public void Open_FeatureDataset_Network(IFeatureDataset pFeatureDataset)
        {
            ClearResult();
            if (!Initialize_NetworkAndMap(pFeatureDataset))
                Console.WriteLine("打开network出错");
        }
        //关闭工作空间
        public void ClearResult()
        {
            m_GeometricNetwork = null;
            // m_PointCollection = null;
            m_PointToEID = null;
            m_EnumNetEID_Edges = null;
            m_EnumNetEID_Junctions = null;
            m_Polyline = null;
        }
        //初始化网络工作空间
        private bool Initialize_NetworkAndMap(IFeatureDataset pFeatureDataset)
        {
            IFeatureClassContainer pFeatureClassContainer;//包括数据和拓扑关系
            IFeatureClass pFeatureClass;
            IGeoDataset pGeoDataset;
            ILayer pLayer;
            IFeatureLayer pFeatureLayer;
            IEnvelope pEnvelope, pEnvelopMax;
            INetworkCollection pNetworkCollection = pFeatureDataset as INetworkCollection;

            int Count = pNetworkCollection.GeometricNetworkCount;
            m_GeometricNetwork = pNetworkCollection.get_GeometricNetwork(0);
            INetwork pNetwork = m_GeometricNetwork.Network;
            double SearchTolerance;

            pFeatureClassContainer = m_GeometricNetwork as IFeatureClassContainer;
            Count = pFeatureClassContainer.ClassCount;

            //int[] Mark = new int[10];
            //int m = 0;
            int j = 0;
            bool t = false;
            int layernumber = m_Map.LayerCount;
            IEnumDataset pEnumDataset = pFeatureDataset.Subsets;
            IDataset pDataset = pEnumDataset.Next();

            while (j < pFeatureClassContainer.ClassCount)
            {
                for (int i = 0; i < m_Map.LayerCount; i++)
                {
                    if (pDataset.Name.ToUpper() == m_Map.get_Layer(i).Name.ToUpper())
                    {
                        //Mark[m++] = i;
                        t = true;
                        continue;
                    }
                }
                if (!t)
                {
                    pFeatureClass = pFeatureClassContainer.get_Class(j);
                    pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = pFeatureClass;
                    pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName;
                    m_Map.AddLayer(pFeatureLayer);
                    layernumber++;
                    // Mark[m++]=
                }
                j++;
                pDataset = pEnumDataset.Next();
            }

            m_ActiveView.Refresh();
            //Count = m_Map.LayerCount;
            pEnvelopMax = new EnvelopeClass();

            for (int i = 0; i < layernumber; i++)
            {
                pLayer = m_Map.get_Layer(i);
                pFeatureLayer = pLayer as IFeatureLayer;
                pGeoDataset = pFeatureLayer as IGeoDataset;
                pEnvelope = pGeoDataset.Extent;
                pEnvelopMax.Union(pEnvelope);
            }
            m_PointToEID = new PointToEIDClass();
            m_PointToEID.SourceMap = m_Map;
            m_PointToEID.GeometricNetwork = m_GeometricNetwork;

            double Width, Height;
            Width = pEnvelopMax.Width;
            Height = pEnvelopMax.Height;

            if (Width > Height)
                SearchTolerance = Width / 100;
            else
                SearchTolerance = Height / 100;

            m_PointToEID.SnapTolerance = SearchTolerance;

            return true;
        }
        //解决路径函数
        public bool SovePath(string WeightName)
        {
            try
            {
                if (m_GeometricNetwork == null)
                {
                    return false;
                }
                int intEdgeUserClassID;
                int intEdgeUserID;
                int intEdgeUserSubID;
                int intEdgeID;
                IPoint pFoundNEdgePoint;
                double EdgePercent;

                INetSolver pNetSolver;
                INetwork pNetwork;
                ITraceFlowSolverGEN pTraceFlowSolverGEN = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
                pNetSolver = pTraceFlowSolverGEN as INetSolver;
                pNetwork = m_GeometricNetwork.Network;
                pNetSolver.SourceNetwork = pNetwork;
                INetElements pNetElements = pNetwork as INetElements;
                if (m_PointCollection == null)
                {
                    MessageBox.Show("请选择点!!");
                    return false;
                }
                int SelectPoint_Number = m_PointCollection.PointCount;
                IEdgeFlag[] pEdgeFlagList = new EdgeFlagClass[SelectPoint_Number];
                for (int i = 0; i < SelectPoint_Number; i++)
                {
                    INetFlag pNetFlag = new EdgeFlagClass() as INetFlag;
                    IPoint pEdgePoint = m_PointCollection.get_Point(i);
                    //查找输入点的最近的边线
                    m_PointToEID.GetNearestEdge(pEdgePoint, out intEdgeID, out pFoundNEdgePoint, out EdgePercent);
                    pNetElements.QueryIDs(intEdgeID, esriElementType.esriETEdge, out intEdgeUserClassID, out intEdgeUserID, out intEdgeUserSubID);
                    pNetFlag.UserClassID = intEdgeUserClassID;
                    pNetFlag.UserID = intEdgeUserID;
                    pNetFlag.UserSubID = intEdgeUserSubID;

                    IEdgeFlag pTemp = (IEdgeFlag)(pNetFlag as IEdgeFlag);
                    pEdgeFlagList[i] = pTemp;
                }

                pTraceFlowSolverGEN.PutEdgeOrigins(ref pEdgeFlagList);
                INetSchema pNetSchema = pNetwork as INetSchema;
                INetWeight pNetWeight = pNetSchema.get_WeightByName(WeightName);//设置权重，有特定的名字
                INetSolverWeights pNetSolverWeights = pTraceFlowSolverGEN as INetSolverWeights;

                pNetSolverWeights.FromToEdgeFilterWeight = pNetWeight;
                pNetSolverWeights.ToFromEdgeFilterWeight = pNetWeight;

                object[] vaRes = new object[SelectPoint_Number - 1];

                pTraceFlowSolverGEN.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum, out m_EnumNetEID_Junctions, out m_EnumNetEID_Edges, SelectPoint_Number - 1, ref vaRes);
                //计算元素成本
                m_PathCost = 0;
                for (int i = 0; i < vaRes.Length; i++)
                {
                    double m_va = (double)vaRes[i];
                    m_PathCost += m_va;
                }
                m_Polyline = null;
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }
        // 形成最短路径的几何形状，根据找到的最近的点（junctions）
        public IPolyline PathPolyLine()
        {
            IEIDInfo pEIDInfo;
            IGeometry pGeometry;
            if (m_Polyline != null) return m_Polyline;

            m_Polyline = new PolylineClass();

            IGeometryCollection pGeometryCollection = m_Polyline as IGeometryCollection;

            ISpatialReference pSpatialReference = m_Map.SpatialReference;
            IEIDHelper pEIDHelper = new EIDHelperClass();
            pEIDHelper.GeometricNetwork = m_GeometricNetwork;
            pEIDHelper.OutputSpatialReference = pSpatialReference;
            pEIDHelper.ReturnGeometries = true;
            IEnumEIDInfo pEnumEIDInfo = pEIDHelper.CreateEnumEIDInfo(m_EnumNetEID_Edges);
            int number = pEnumEIDInfo.Count;
            pEnumEIDInfo.Reset();
            for (int i = 0; i < number; i++)
            {
                pEIDInfo = pEnumEIDInfo.Next();
                pGeometry = pEIDInfo.Geometry;
                pGeometryCollection.AddGeometryCollection(pGeometry as IGeometryCollection);
            }
            return m_Polyline;
        }
        //查找最短路径
        private void label37_Click(object sender, EventArgs e)
        {
            if (SovePath("Weight"))
            {
                IPolyline pPolylineResult = PathPolyLine();//最后返回最短路径
                flagbool = false;
                if (pPolylineResult.IsEmpty)
                {
                    MessageBox.Show("没有路径可到!!");
                }
                else
                {
                    IRgbColor color = new RgbColorClass();
                    color.Red = 500;
                    IElement element = new LineElementClass();
                    ILineSymbol linesymbol = new SimpleLineSymbolClass();
                    linesymbol.Color = color as IColor;
                    linesymbol.Width = 500;
                    element.Geometry = m_Polyline;
                    m_GraphicsContainer.AddElement(element, 5);
                    m_ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                }
            }
            axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;
            m_PointCollection = null;
            this.label37.Visible = false;
        }
        #endregion
       

        private void label39_Click(object sender, EventArgs e)
        {
        }

        private void label25_Click(object sender, EventArgs e)
        {
            this.panel050.Parent = this.axMapControl1;
            this.panel050.Visible = true;
            this.panel052.Visible = true;
            this.panel050.BringToFront();
        }

        private void label38_Click(object sender, EventArgs e)
        {

        }

        private void label40_VisibleChanged(object sender, EventArgs e)
        {

        }

        private void label38_Click_1(object sender, EventArgs e)
        {
            this.panel050.Visible = false;
        }

        private void button02_Click(object sender, EventArgs e)
        {


            this.axMapControl1.Map.ClearSelection();
            IFeatureLayer pFeatureLayer=null;
            for (int i = 0; i < this.axMapControl1.Map.LayerCount; i++)
            {
                if (axMapControl1.get_Layer(i).Name == "地名")
                {
                    pFeatureLayer = axMapControl1.get_Layer(i) as IFeatureLayer;
                }
            }
            if (pFeatureLayer == null)
            {
                MessageBox.Show("请输入图层！", "提示");
                return;
            }
            IClone pClone = pFeatureLayer.FeatureClass.Fields as IClone;
            IFields pFields = pClone.Clone() as IFields;
           
            IQueryFilter pQueryFilter1 = new QueryFilter();
            pQueryFilter1.WhereClause = "OBJECTID" + "=" + textBox02.Text;
            pQueryFilter1.WhereClause = "name like '%" + textBox02.Text + "%'";

            IQueryFilter pQueryFilter2 = new QueryFilter();
            pQueryFilter2.WhereClause = "OBJECTID" + "=" + textBox03.Text;
            pQueryFilter2.WhereClause = "name like '%" + textBox03.Text + "%'";
            try
            {

                IFeatureCursor pFeatureCursor = pFeatureLayer.FeatureClass.Search(pQueryFilter1, false);
                IFeatureCursor pFeatureCursor2 = pFeatureLayer.FeatureClass.Search(pQueryFilter2, false);
                IFeature pFeature = pFeatureCursor.NextFeature();
                IFeature pFeature2 = pFeatureCursor2.NextFeature();
                if (m_PointCollection == null)
                {
                    m_PointCollection = new MultipointClass();
                }
                if (pFeature != null)
                {

                    object o = Type.Missing;
                    IPoint point = pFeature.Shape as IPoint;
                   
                    this.axMapControl1.CenterAt(point);
                    this.axMapControl1.Map.SelectFeature(pFeatureLayer, pFeature);

                    IPoint point2 = pFeature.Shape as IPoint;
                    this.axMapControl1.CenterAt(point2);
                    this.axMapControl1.Map.SelectFeature(pFeatureLayer, pFeature2);
                    m_PointCollection.AddPoint(point, ref o, ref o);
                    m_PointCollection.AddPoint(point2, ref o, ref o);
                }
                if (SovePath("Weight"))
                {
                    IPolyline pPolylineResult = PathPolyLine();//最后返回最短路径
                    flagbool = false;
                    if (pPolylineResult.IsEmpty)
                    {
                        MessageBox.Show("没有路径可到!!");
                    }
                    else
                    {
                        IRgbColor color = new RgbColorClass();
                        color.Red = 500;
                        IElement element = new LineElementClass();
                        ILineSymbol linesymbol = new SimpleLineSymbolClass();
                        linesymbol.Color = color as IColor;
                        linesymbol.Width = 500;
                        element.Geometry = m_Polyline;
                        m_GraphicsContainer.AddElement(element, 5);
                        m_ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                    }
                }
                axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;
                m_PointCollection = null;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void panel052_Paint(object sender, PaintEventArgs e)
        { 
        }

        private void label38_Click_2(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void label39_Click_1(object sender, EventArgs e)
        {
            this.panel050.Visible = false;
        }


    }
}
